<?php

namespace app\common\service;

use app\common\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;

class CommonGoodsCateService
{

    use InstanceTrait;

    /** 根据上级分类查询所有下级分类
     * @param int $cateId
     * @return Query
     */
    public function childrenQuery(int $cateId): Query
    {

        return Db::table(" (
	SELECT
		@ids AS _ids,
		@l:=@l+1 AS level,
		(SELECT @ids := GROUP_CONCAT( id ) FROM `goods_cate` WHERE FIND_IN_SET( pid, @ids )) cids 
	FROM
		`goods_cate`,
		( SELECT @ids:=$cateId , @l:=0) pid 
	) AS scope,
	`goods_cate`  ")
            ->whereRaw(" scope._ids IS NOT NULL AND FIND_IN_SET( goods_cate.id, scope._ids ) AND goods_cate.id<>$cateId ");
    }

    /**
     * 根据上级分类ID查询出所有子孙分类
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getChildren(int $cateId): array|\think\Collection
    {
        return $this->childrenQuery($cateId)->select();
    }

    /**
     * 根据上级分类ID，查询出所有子孙分类ID集合
     * @param int $cateId
     * @return array
     */
    public function getChildrenIds(int $cateId): array
    {
        return $this->childrenQuery($cateId)->column("id");
    }

}
